import re
from datetime import datetime
from random import  randint

from flask import g

from info.libs.yuntongxun.sms import CCP
from flask import render_template
from flask import request, jsonify
from flask import session

from info import redis_store, db
from info.models import User
from info.utils.common import pro_blue
from . import passport_blue
from info.utils.captcha.captcha import captcha


@passport_blue.route('/api/v1.0/imagecode')          #图片验证码发送
def imagecode():
    cur=request.args.get('cur')
    pre = request.args.get('pre')
    if not cur:
        return jsonify(errno=1,errmsg='图片验证码未发送')
    name, text, image = captcha.generate_captcha()
    redis_store.setex('img:%s'%cur,60,text)
    if pre:
        redis_store.delete('img:%s'%pre)
    return image
@passport_blue.route('/api/v1.0/smscode',methods=['POST'])          #短信验证码发送
def smscode():
    mobile=request.json.get('mobile')
    image_code=request.json.get('image_code')
    image_code_id=request.json.get('image_code_id')
    image_code_session=redis_store.get('img:%s'%image_code_id)
    if not all([image_code,image_code_id]):
        return jsonify(errno=1,errmsg='参数不全')
    if not image_code_session:
        return jsonify(errno=1, errmsg='图片验证码已过期')
    if not re.match(r"^1[35678]\d{9}$", mobile):
        return jsonify(errno=1, errmsg='手机号格式错误')
    if not (image_code.upper()==image_code_session.upper()):
        return jsonify(errno=1, errmsg='图片验证码不对')
    redis_store.delete('img:%s' % image_code_id)
    i=randint(0,999999)
    i='%06d'%i
    ccp=CCP()
    errno=ccp.send_template_sms(mobile, [i, 5], 1)
    if errno==0:
        redis_store.setex(mobile,60,i)
        return jsonify(errno=0, errmsg='成功')
    else:
        return jsonify(errno=1, errmsg='发送失败')
@passport_blue.route('/api/v1.0/user',methods=['POST','GET'])             #账号注册/获取登陆状态
@pro_blue
def user():
    if request.method=='GET':
        if g.user:
            return jsonify(errno=0,errmsg='ok',data=g.user.to_dict())
    mobile=request.json.get('mobile')
    phonecode=request.json.get('phonecode')
    password=request.json.get('password')
    if not all([mobile,phonecode,password]):
        return jsonify(errno=1,errmsg='参数不全')
    if not re.match(r"^1[35678]\d{9}$", mobile):
        return jsonify(errno=1, errmsg='手机号格式错误')
    phonecode_session=redis_store.get(mobile)
    if not phonecode_session:
        return jsonify(errno=1, errmsg='手机验证码过期')
    if not phonecode_session==phonecode:
        return jsonify(errno=1, errmsg='手机验证码错误')
    if not re.match(r"^(\d{6,20}$)", password):
        return jsonify(errno=1, errmsg='密码由6-20位的字母与数字组成，密码格式不对')
    redis_store.delete(mobile)
    user=User()
    user.name='老王'
    user.mobile=mobile
    user.password=password
    user.create_time=datetime.now()
    db.session.add(user)
    db.session.commit()
    return jsonify(errno=0, errmsg='注册成功')
@passport_blue.route('/api/v1.0/session',methods=['POST','GET','DELETE'])
@pro_blue
def session_ww():
    if request.method=='POST':          #账号登陆
        mobile=request.json.get('mobile')
        password=request.json.get('password')
        if not all([mobile,password]):
            return jsonify(errno=1, errmsg='参数不全')
        user=User.query.filter(User.mobile==mobile).first()
        if not user:
            return jsonify(errno=1, errmsg='该账号不存在')
        if not user.check_passowrd(password):
            return jsonify(errno=1, errmsg='密码错误')
        session['user_id']=user.id
        user.update_time=datetime.now()
        db.session.commit()
        return jsonify(errno=0, errmsg='登陆成功')
    elif request.method=='DELETE':
        user_id = session.get('user_id')
        if not user_id:
            return jsonify(errno=4101, errmsg='未登录')
        user = User.query.filter(User.id == user_id).first()
        if not user:
            return jsonify(errno=4101, errmsg='未登录')
        session.pop('user_id')
        return jsonify(errno=0, errmsg='ok')
    elif request.method=='GET':
        if g.user:
            data={
                "name": g.user.name,
                "user_id": g.user.id
            }
            return jsonify(errno=0, errmsg='ok',data=data)
        else:
            return jsonify(errno=4101, errmsg='未登录')



